#include <gst/gst.h>
#include <glib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <sys/time.h>
#include <assert.h>
// #include <zmq.h>
#include "gstnvdsmeta.h"
//#include "gstnvstreammeta.h"
#ifndef PLATFORM_TEGRA
#include "gst-nvmessage.h"
//#include "rtsp_demo.h"
// #include "include/httpClient.h"
#endif

#define MAX_DISPLAY_LEN 64

#define PGIE_CLASS_ID_VEHICLE 0
#define PGIE_CLASS_ID_PERSON 2

/* By default, OSD process-mode is set to CPU_MODE. To change mode, set as:
 * 1: GPU mode (for Tesla only)
 * 2: HW mode (For Jetson only)
 */
#define OSD_PROCESS_MODE 2

/* By default, OSD will not display text. To display text, change this to 1 */
#define OSD_DISPLAY_TEXT 0

/* The muxer output resolution must be set if the input streams will be of
 * different resolution. The muxer will scale all the input frames to this
 * resolution. */
// #define MUXER_OUTPUT_WIDTH 1920
// #define MUXER_OUTPUT_HEIGHT 1080
#define MUXER_OUTPUT_WIDTH 1280
#define MUXER_OUTPUT_HEIGHT 720

/* Muxer batch formation timeout, for e.g. 40 millisec. Should ideally be set
 * based on the fastest source's framerate. */
#define MUXER_BATCH_TIMEOUT_USEC 40000

// #define TILED_OUTPUT_WIDTH 1920
// #define TILED_OUTPUT_HEIGHT 1080
#define TILED_OUTPUT_WIDTH 1280
#define TILED_OUTPUT_HEIGHT 720

#define RENDER_REGIONS_AND_PERSON_COUNT 1

/* NVIDIA Decoder source pad memory feature. This feature signifies that source
 * pads having this capability will push GstBuffers containing cuda buffers. */
#define GST_CAPS_FEATURES_NVMM "memory:NVMM"

gchar pgie_classes_str[4][32] = { "Vehicle", "TwoWheeler", "Person",
  "RoadSign"
};

#define FPS_PRINT_INTERVAL 300

#define NVDS_USER_FRAME_META_EXAMPLE (nvds_get_user_meta_type("NVIDIA.NVINFER.USER_META"))

#define USER_ARRAY_SIZE 16


//static struct timeval start_time = { };

//static guint probe_counter = 0;

/* tiler_sink_pad_buffer_probe  will extract metadata received on OSD sink pad
 * and update params for drawing rectangle, object information etc. */


void *set_metadata_ptr(void);
static gpointer copy_user_meta(gpointer data, gpointer user_data);
static void release_user_meta(gpointer data, gpointer user_data);

#define MAX_MISS_FRAMES 45
#define PERSON_THRESH 0.6
#define STAY_TIME_HTRESH 2
#define WARN_T_THRES 1.0

extern double what_time_is_it_now();

typedef struct {
    int left;
    int top;
    int right;
    int bottom;
    int n_person_in;
    int n_total_call;

    double stay_time_thresh;
    double latest_no_person_time;
    double person_in_dur;
} region ;

typedef struct 
{
  int event_happen;
  double region_time_a;
  double region_time_b;
  double region_time_c;
  int person_num;
}event_result_frame;

// create publisher
void *context;
// create publisher
void *publisher;
char* community;
char *cameraid;
region *REGIONS = NULL;
//gdouble check_stay_in_time(region *r_to_b_check,gint person_x,gint person_y);
// input regin and person center(x, y)
gdouble check_stay_in_time_for_real(region *r_to_b_check,gint person_x,gint person_y)
{
    r_to_b_check->n_total_call++;
    if(person_x>=r_to_b_check->left&&person_x<=r_to_b_check->right&&person_y>=r_to_b_check->top&&person_y<=r_to_b_check->bottom)
    {
        r_to_b_check->n_person_in++;
        r_to_b_check->person_in_dur = what_time_is_it_now()-r_to_b_check->latest_no_person_time;
    }else if ((r_to_b_check->n_total_call - r_to_b_check->n_person_in > MAX_MISS_FRAMES) && (r_to_b_check->n_person_in>0))
    {
        r_to_b_check->latest_no_person_time = what_time_is_it_now();
        r_to_b_check->n_person_in = 0;
        r_to_b_check->n_total_call = 0;
        if (r_to_b_check->person_in_dur < r_to_b_check->stay_time_thresh)
        {   
            return r_to_b_check->person_in_dur;
        }else
        {
            r_to_b_check->person_in_dur=0;
            return r_to_b_check->person_in_dur;
        }        
    }else if ((r_to_b_check->n_total_call > MAX_MISS_FRAMES)&& (r_to_b_check->n_person_in==0))
    {
        r_to_b_check->latest_no_person_time = what_time_is_it_now();
    }
    
    return 0;
}

// input regin and person center(x, y)
bool point_in_region(region *r_to_b_check,int person_x,int person_y){

  bool in_res = false;
  if ((person_x>=r_to_b_check->left)&&(person_x<=r_to_b_check->right)&&(person_y>=r_to_b_check->top)&&(person_y<=r_to_b_check->bottom))
  {
    in_res = true;
  }

  return in_res;
}



double check_stay_in_time(region *r_to_b_check,int person_x,int person_y)
{   
    // if (!r_to_b_check->n_total_call && !r_to_b_check->n_person_in)
    // {
    //   r_to_b_check->person_in_dur=0;
    // }    
    r_to_b_check->n_total_call++;
    if(point_in_region(r_to_b_check,person_x,person_y))
    {
        r_to_b_check->n_person_in++;
        r_to_b_check->person_in_dur = what_time_is_it_now()-r_to_b_check->latest_no_person_time;
        //return r_to_b_check->person_in_dur;
    }else if ((r_to_b_check->n_total_call - r_to_b_check->n_person_in > MAX_MISS_FRAMES) && (r_to_b_check->n_person_in>0))
    {
        r_to_b_check->latest_no_person_time = what_time_is_it_now();
        r_to_b_check->n_person_in = 0;
        r_to_b_check->n_total_call = 0;
        g_print("[region debug]: the time is %.2lf\n",r_to_b_check->person_in_dur);

        r_to_b_check->person_in_dur=0;
    }else if(!r_to_b_check->n_person_in)
    {
      r_to_b_check->latest_no_person_time = what_time_is_it_now();
    }

    return r_to_b_check->person_in_dur;
}


void region_init(region *r ,gint left,gint top,gint right,gint bottom,gdouble stay_time_thresh,gdouble create_time)
{
  r->top = top;
  r->left = left;
  r->right = right;
  r->bottom = bottom;
  r->n_person_in = 0;
  r->n_total_call = 0;
  r->stay_time_thresh = stay_time_thresh;
  r->latest_no_person_time = create_time;
  r->person_in_dur = 0;
}


extern double what_time_is_it_now()
{
    struct timeval time;
    if (gettimeofday(&time,NULL)){
        return 0;
    }
    return (double)time.tv_sec + (double)time.tv_usec * .000001;
}


void *set_metadata_ptr()
{
  int i = 0;
  gchar *user_metadata = (gchar*)g_malloc0(USER_ARRAY_SIZE);

  //g_print("\n**************** Setting user metadata array of 16 on nvinfer src pad\n");
  for(i = 0; i < USER_ARRAY_SIZE; i++) {
    user_metadata[i] = rand() % 255;
    //g_print("user_meta_data [%d] = %d\n", i, user_metadata[i]);
  }
  return (void *)user_metadata;
}

/* copy function set by user. "data" holds a pointer to NvDsUserMeta*/
static gpointer copy_user_meta(gpointer data, gpointer user_data)
{
  NvDsUserMeta *user_meta = (NvDsUserMeta *)data;
  gchar *src_user_metadata = (gchar*)user_meta->user_meta_data;
  gchar *dst_user_metadata = (gchar*)g_malloc0(USER_ARRAY_SIZE);
  memcpy(dst_user_metadata, src_user_metadata, USER_ARRAY_SIZE);
  return (gpointer)dst_user_metadata;
}

/* release function set by user. "data" holds a pointer to NvDsUserMeta*/
static void release_user_meta(gpointer data, gpointer user_data)
{
  NvDsUserMeta *user_meta = (NvDsUserMeta *) data;
  if(user_meta->user_meta_data) {
    g_free(user_meta->user_meta_data);
    user_meta->user_meta_data = NULL;
  }
}

void *set_event_result_ptr(double time_a ,double time_b,double time_c,int person_num)
{
  event_result_frame * event_res = (event_result_frame*)malloc(sizeof(event_result_frame));
  event_res->region_time_a = time_a;
  event_res->region_time_b = time_b;
  event_res->region_time_c = time_c;
  event_res-> event_happen = 0;
  if (time_a || time_b || time_c)
  {
    event_res-> event_happen = 1;
  }
  event_res->person_num = person_num;
  return (void * ) event_res;
  
}

static gpointer copy_event_res(gpointer data,gpointer user_data){

  NvDsUserMeta *user_meta = (NvDsUserMeta *)data;
  event_result_frame *src_user_metadata = (event_result_frame *)user_meta->user_meta_data;
  event_result_frame *dst_user_metadata = (event_result_frame *)malloc(sizeof(event_result_frame));
  memcpy(dst_user_metadata, src_user_metadata,1);
  return (gpointer) dst_user_metadata;
}

static void release_event_res(gpointer data,gpointer user_data){
  NvDsUserMeta *user_meta = (NvDsUserMeta *) data;
  if(user_meta->user_meta_data){
    free(user_meta->user_meta_data);
    user_meta->user_meta_data = NULL;
  }
}

/* osd_sink_pad_buffer_probe  will extract metadata received on OSD sink pad
 * and update params for drawing rectangle, object information etc. */

static GstPadProbeReturn
osd_sink_pad_buffer_probe (GstPad * pad, GstPadProbeInfo * info,
    gpointer u_data)
{
  GstBuffer *buf = (GstBuffer *) info->data;
  NvDsMetaList * l_frame = NULL;
  NvDsMetaList * l_user_meta = NULL;
  NvDsUserMeta *user_meta = NULL;
  gchar *user_meta_data = NULL;
  int i = 0;

  NvDsBatchMeta *batch_meta = gst_buffer_get_nvds_batch_meta (buf);

  for (l_frame = batch_meta->frame_meta_list; l_frame != NULL;
      l_frame = l_frame->next) {
    NvDsFrameMeta *frame_meta = (NvDsFrameMeta *) (l_frame->data);
    /* Validate user meta */
    for (l_user_meta = frame_meta->frame_user_meta_list; l_user_meta != NULL;
        l_user_meta = l_user_meta->next) {
      user_meta = (NvDsUserMeta *) (l_user_meta->data);
      user_meta_data = (gchar *)user_meta->user_meta_data;

      if(user_meta->base_meta.meta_type == NVDS_USER_FRAME_META_EXAMPLE)
      {/*
        g_print("\n************ Retrieving user_meta_data array of 16 on osd sink pad\n");
        for(i = 0; i < USER_ARRAY_SIZE; i++) {
          g_print("user_meta_data [%d] = %d\n", i, user_meta_data[i]);
        }*/
        g_print("\n");
      }
    }
    //frame_number++;
  }
  return GST_PAD_PROBE_OK;
}



static GstPadProbeReturn
osd_sink_pad_buffer_res_probe (GstPad * pad, GstPadProbeInfo * info,
    gpointer u_data)
{
  GstBuffer *buf = (GstBuffer *) info->data;
  NvDsMetaList * l_frame = NULL;
  NvDsMetaList * l_user_meta = NULL;
  NvDsUserMeta *user_meta = NULL;
  event_result_frame *user_meta_data = NULL;
  NvDsDisplayMeta *display_meta = NULL;
  NvDsBatchMeta *batch_meta = gst_buffer_get_nvds_batch_meta (buf);
  region *r = REGIONS;
  int b = 0;

  for (l_frame = batch_meta->frame_meta_list; l_frame != NULL;
      l_frame = l_frame->next) {
    NvDsFrameMeta *frame_meta = (NvDsFrameMeta *) (l_frame->data);
    /* Validate user meta */
    for (l_user_meta = frame_meta->frame_user_meta_list; l_user_meta != NULL;
        l_user_meta = l_user_meta->next) {
      user_meta = (NvDsUserMeta *) (l_user_meta->data);
      user_meta_data = (event_result_frame *)user_meta->user_meta_data;

      if(user_meta->base_meta.meta_type == NVDS_USER_FRAME_META_EXAMPLE)
      {/*
        g_print("\n************ Retrieving user_meta_data array of 16 on osd sink pad\n");
        for(i = 0; i < USER_ARRAY_SIZE; i++) {
          g_print("user_meta_data [%d] = %d\n", i, user_meta_data[i]);
        }*/
        
    }
    }
    //frame_number++;

  }
  return GST_PAD_PROBE_OK;
}



/* Set nvds user metadata at frame level. User need to set 4 parameters after
 * acquring user meta from pool using nvds_acquire_user_meta_from_pool().
 *
 * Below parameters are required to be set.
 * 1. user_meta_data : pointer to User specific meta data
 * 2. meta_type: Metadata type that user sets to identify its metadata
 * 3. copy_func: Metadata copy or transform function to be provided when there
 *               is buffer transformation
 * 4. release_func: Metadata release function to be provided when it is no
 *                  longer required.
 *
 * osd_sink_pad_buffer_probe  will extract metadata received on OSD sink pad
 * and update params for drawing rectangle, object information etc. */

static GstPadProbeReturn
nvinfer_src_pad_buffer_probe (GstPad * pad, GstPadProbeInfo * info,
    gpointer u_data)
{
  GstBuffer *buf = (GstBuffer *) info->data;
  NvDsMetaList * l_frame = NULL;
  NvDsUserMeta *user_meta = NULL;
  NvDsMetaType user_meta_type = NVDS_USER_FRAME_META_EXAMPLE;

  NvDsBatchMeta *batch_meta = gst_buffer_get_nvds_batch_meta (buf);

    for (l_frame = batch_meta->frame_meta_list; l_frame != NULL;
      l_frame = l_frame->next) {
        NvDsFrameMeta *frame_meta = (NvDsFrameMeta *) (l_frame->data);

        /* Acquire NvDsUserMeta user meta from pool */
        user_meta = nvds_acquire_user_meta_from_pool(batch_meta);

        /* Set NvDsUserMeta below */
        user_meta->user_meta_data = (void *)set_metadata_ptr();
        user_meta->base_meta.meta_type = user_meta_type;
        user_meta->base_meta.copy_func = (NvDsMetaCopyFunc)copy_user_meta;
        user_meta->base_meta.release_func = (NvDsMetaReleaseFunc)release_user_meta;

        /* We want to add NvDsUserMeta to frame level */
        nvds_add_user_meta_to_frame(frame_meta, user_meta);
    }
    return GST_PAD_PROBE_OK;
}



static GstPadProbeReturn
tiler_src_pad_buffer_probe (GstPad * pad, GstPadProbeInfo * info,
    gpointer u_data)
{
    GstBuffer *buf = (GstBuffer *) info->data;
    
    NvDsObjectMeta *obj_meta = NULL;
    NvDsUserMeta *user_meta = NULL;
    guint vehicle_count = 0;
    
    NvDsMetaList * l_frame = NULL;
    NvDsMetaList * l_obj = NULL;
    NvDsDisplayMeta *display_meta = NULL;
    NvDsMetaType user_meta_type = NVDS_USER_FRAME_META_EXAMPLE;
    NvDsBatchMeta *batch_meta = gst_buffer_get_nvds_batch_meta (buf);
    region *r = REGIONS;
    int b = 0;

    for (l_frame = batch_meta->frame_meta_list; l_frame != NULL;
      l_frame = l_frame->next) {
        NvDsFrameMeta *frame_meta = (NvDsFrameMeta *) (l_frame->data);
        user_meta = nvds_acquire_user_meta_from_pool(batch_meta);
        double region_time_a=0;
        double region_time_b=0;
        double region_time_c=0;
        double region__a=0;
        double region__b=0;
        double region__c=0;
        guint person_count = 0;
        guint num_rects = 0;
        //double thresh_max = 0;
        int bbox_center_x = 0;
        int bbox_center_y = 0;
        int region_persons[3] = {0};

        gint offset = 0;
        
        for (l_obj = frame_meta->obj_meta_list; l_obj != NULL;
                l_obj = l_obj->next) {
            obj_meta = (NvDsObjectMeta *) (l_obj->data);
                num_rects++;
                person_count++;
                char send_buf[256];
                sprintf(send_buf,"community:%s",obj_meta->class_id);
                printf("%s\n",send_buf);
            // int re = zmq_send(publisher, send_buf, strlen(send_buf)+1, 0);
            
          // }
        }
        user_meta->user_meta_data = (void *)set_event_result_ptr(region_time_a,region_time_b,region_time_c,person_count);
        user_meta->base_meta.meta_type = user_meta_type;
        user_meta->base_meta.copy_func = (NvDsMetaCopyFunc)copy_event_res;
        user_meta->base_meta.release_func = (NvDsMetaReleaseFunc)release_event_res;

        event_result_frame * user_meta_data= (event_result_frame *)user_meta->user_meta_data;
        nvds_add_user_meta_to_frame(frame_meta, user_meta);

#if RENDER_REGIONS_AND_PERSON_COUNT
        display_meta = nvds_acquire_display_meta_from_pool(batch_meta);
        NvOSD_TextParams *txt_params  = &display_meta->text_params;
        txt_params->display_text = g_malloc0 (MAX_DISPLAY_LEN);
        offset = snprintf(txt_params->display_text, MAX_DISPLAY_LEN,\
         "person: %d \narea A: %.2lf s area B: %.2lf s area C: %.2lf s", \
        person_count,region__a,region__b,region__c);
        //g_print("a : %.2lf s  b :%.2lf s  c : %.2lf s\n",region__a,region__b,region__c);
        display_meta->num_rects = num_rects+3;
        display_meta->num_labels = person_count+1;
        NvOSD_RectParams *rect_params = &(display_meta->rect_params);


        /* Now set the offsets where the string should appear */
        txt_params->x_offset = 10;
        txt_params->y_offset = 12;

        /* Font , font-color and font-size */
        txt_params->font_params.font_name = "Serif";
        txt_params->font_params.font_size = 10;
        txt_params->font_params.font_color.red = 1.0;
        txt_params->font_params.font_color.green = 1.0;
        txt_params->font_params.font_color.blue = 1.0;
        txt_params->font_params.font_color.alpha = 1.0;

        /* Text background color */
        txt_params->set_bg_clr = 1;
        txt_params->text_bg_clr.red = 0.0;
        txt_params->text_bg_clr.green = 0.0;
        txt_params->text_bg_clr.blue = 0.0;
        txt_params->text_bg_clr.alpha = 1.0;

        for(int i = 0;i<3;i++){
          (rect_params+i)->left = (r+3*b+i)->left;
          (rect_params+i)->top = (r+3*b+i)->top;
          (rect_params+i)->width = (r+3*b+i)->right - (r+3*b+i)->left;
          (rect_params+i)->height = (r+3*b+i)->bottom - (r+3*b+i)->top;
          (rect_params+i)->border_width= 5;
          (rect_params+i)->border_color.red = 0;
          (rect_params+i)->border_color.green = 0;
          (rect_params+i)->border_color.blue = 1;
          (rect_params+i)->border_color.alpha = 0;
          (rect_params+i)->has_bg_color = 0;
          (rect_params+i)->color_id = 1;
        }

        nvds_add_display_meta_to_frame(frame_meta, display_meta);
#endif
        b++;
    }
    // nvds_add_display_meta_to_frame(frame_meta, display_meta);
    return GST_PAD_PROBE_OK;
}

static gboolean
bus_call (GstBus * bus, GstMessage * msg, gpointer data)
{
  GMainLoop *loop = (GMainLoop *) data;
  switch (GST_MESSAGE_TYPE (msg)) {
    case GST_MESSAGE_EOS:
      g_print ("End of stream\n");
      g_main_loop_quit (loop);
      break;
    case GST_MESSAGE_WARNING:
    {
      gchar *debug;
      GError *error;
      gst_message_parse_warning (msg, &error, &debug);
      g_printerr ("WARNING from element %s: %s\n",
          GST_OBJECT_NAME (msg->src), error->message);
      g_free (debug);
      g_printerr ("Warning: %s\n", error->message);
      g_error_free (error);
      break;
    }
    case GST_MESSAGE_ERROR:
    {
      gchar *debug;
      GError *error;
      gst_message_parse_error (msg, &error, &debug);
      g_printerr ("ERROR from element %s: %s\n",
          GST_OBJECT_NAME (msg->src), error->message);
      if (debug)
        g_printerr ("Error details: %s\n", debug);
      g_free (debug);
      g_error_free (error);
      g_main_loop_quit (loop);
      break;
    }
#ifndef PLATFORM_TEGRA
    case GST_MESSAGE_ELEMENT:
    {
      if (gst_nvmessage_is_stream_eos (msg)) {
        guint stream_id;
        if (gst_nvmessage_parse_stream_eos (msg, &stream_id)) {
          g_print ("Got EOS from stream %d\n", stream_id);
        }
      }
      break;
    }
#endif
    default:
      break;
  }
  return TRUE;
}

static void
cb_newpad (GstElement * decodebin, GstPad * decoder_src_pad, gpointer data)
{
  g_print ("In cb_newpad\n");
  GstCaps *caps = gst_pad_get_current_caps (decoder_src_pad);
  const GstStructure *str = gst_caps_get_structure (caps, 0);
  const gchar *name = gst_structure_get_name (str);
  GstElement *source_bin = (GstElement *) data;
  GstCapsFeatures *features = gst_caps_get_features (caps, 0);

  /* Need to check if the pad created by the decodebin is for video and not
   * audio. */
  if (!strncmp (name, "video", 5)) {
    /* Link the decodebin pad only if decodebin has picked nvidia
     * decoder plugin nvdec_*. We do this by checking if the pad caps contain
     * NVMM memory features. */
    if (gst_caps_features_contains (features, GST_CAPS_FEATURES_NVMM)) {
      /* Get the source bin ghost pad */
      GstPad *bin_ghost_pad = gst_element_get_static_pad (source_bin, "src");
      if (!gst_ghost_pad_set_target (GST_GHOST_PAD (bin_ghost_pad),
              decoder_src_pad)) {
        g_printerr ("Failed to link decoder src pad to source bin ghost pad\n");
      }
      gst_object_unref (bin_ghost_pad);
    } else {
      g_printerr ("Error: Decodebin did not pick nvidia decoder plugin.\n");
    }
  }
}

static void
decodebin_child_added (GstChildProxy * child_proxy, GObject * object,
    gchar * name, gpointer user_data)
{
  g_print ("Decodebin child added: %s\n", name);
  if (g_strrstr (name, "decodebin") == name) {
    g_signal_connect (G_OBJECT (object), "child-added",
        G_CALLBACK (decodebin_child_added), user_data);
  }
}

static GstElement *
create_source_bin (guint index, gchar * uri)
{
  GstElement *bin = NULL, *uri_decode_bin = NULL;
  gchar bin_name[16] = { };

  g_snprintf (bin_name, 15, "source-bin-%02d", index);
  /* Create a source GstBin to abstract this bin's content from the rest of the
   * pipeline */
  bin = gst_bin_new (bin_name);

  /* Source element for reading from the uri.
   * We will use decodebin and let it figure out the container format of the
   * stream and the codec and plug the appropriate demux and decode plugins. */
  uri_decode_bin = gst_element_factory_make ("uridecodebin", "uri-decode-bin");

  if (!bin || !uri_decode_bin) {
    g_printerr ("One element in source bin could not be created.\n");
    return NULL;
  }

  /* We set the input uri to the source element */
  g_object_set (G_OBJECT (uri_decode_bin), "uri", uri, NULL);

  /* Connect to the "pad-added" signal of the decodebin which generates a
   * callback once a new pad for raw data has beed created by the decodebin */
  g_signal_connect (G_OBJECT (uri_decode_bin), "pad-added",
      G_CALLBACK (cb_newpad), bin);
  g_signal_connect (G_OBJECT (uri_decode_bin), "child-added",
      G_CALLBACK (decodebin_child_added), bin);

  gst_bin_add (GST_BIN (bin), uri_decode_bin);

  /* We need to create a ghost pad for the source bin which will act as a proxy
   * for the video decoder src pad. The ghost pad will not have a target right
   * now. Once the decode bin creates the video decoder and generates the
   * cb_newpad callback, we will set the ghost pad target to the video decoder
   * src pad. */
  if (!gst_element_add_pad (bin, gst_ghost_pad_new_no_target ("src",
              GST_PAD_SRC))) {
    g_printerr ("Failed to add ghost pad in source bin\n");
    return NULL;
  }

  return bin;
}

#define SOURCE 1
#define W_H 2
#define REGION_COORD 3
#define END_SOURCE 4
#define END_FILE 5
#define PORT 6

void malloc_error()
{
    fprintf(stderr, "xMalloc error - possibly out of CPU RAM \n");
    exit(EXIT_FAILURE);
}

void realloc_error()
{
    fprintf(stderr, "Realloc error - possibly out of CPU RAM \n");
    exit(EXIT_FAILURE);
}

void *xmalloc(size_t size) {
    void *ptr=malloc(size);
    if(!ptr) {
        malloc_error();
    }
    return ptr;
}

void *xrealloc(void *ptr, size_t size) {
    ptr=realloc(ptr,size);
    if(!ptr) {
        realloc_error();
    }
    return ptr;
}

void strip(char *s)
{
    size_t i;
    size_t len = strlen(s);
    size_t offset = 0;
    for(i = 0; i < len; ++i){
        char c = s[i];
        if(c==' '||c=='\t'||c=='\n'||c =='\r'||c==0x0d||c==0x0a) ++offset;
        else s[i-offset] = c;
    }
    s[len-offset] = '\0';
}
char *fgetl(FILE *fp)
{   
    // int INT_MAX = 256;
    if(feof(fp)) return 0;
    size_t size = 128;
    char* line = (char*)xmalloc(size * sizeof(char));
    if(!fgets(line, size, fp)){
        free(line);
        return 0;
    }
    size_t curr = strlen(line);
    if(curr >= 2)
        if(line[curr-2] == 0x0d) line[curr-2] = 0x00;

    if(curr >= 1)
        if(line[curr-1] == 0x0a) line[curr-1] = 0x00;

    return line;
}

int get_int(char* rline, int *arr){
    int i = 0;
    char* token = strtok(rline,":");
    char* temp = strtok(NULL,":");
    char* token2 = strtok(temp,",");
    while(token2 != NULL){
        arr[i] = atoi(token2);
        i++;
        token2 = strtok(NULL,",");
    }
    return i;
}

int get_type(char * line){
    char c = line[0];
    if(c == '\0') return 0;
    else if(c == '#') return 0;
    else if(c == '[') return 1;
    else if(c == 'w') return 2;
    else if(c == 'r') return 3;
    else if(c == '-') return 4;
    else if(c == '=') return 5;
    else if(c== 'p') return 6;
    else return -1;
    return 0;
}

void get_region(FILE* fp, int* num_source, int *rect, int *wh,
 int *region_num_list, int * total_region, int* port){

    int num_region = 0;
    int num = 0;
    char * cfgLine;

    while((cfgLine=fgetl(fp)) != 0){
        strip(cfgLine);
        int type = get_type(cfgLine);
        if (type <= 0) continue;
        // 1
        if(type == SOURCE){
            (*num_source)++;
        }
        // 2
        else if(type == W_H){
            num = get_int(cfgLine, wh+(*num_source-1)*2);
            if (num != 2){
                printf("source w_h define error, check region_config file\n");
                exit(EXIT_FAILURE);
            }
            // printf("sizeof(wh):%ld\n",sizeof(wh));
            // for(int n=0;n<(*num_source)*2;n++){
            //     printf("wh: %d\n",wh[n]);
            // }
        }
        // 3
        else if(type == REGION_COORD){
            num_region++;
            (*total_region)++;
            num = get_int(cfgLine,rect+(*total_region-1)*4);
            if (num != 4){
                printf("source region coord define error, check region_config file\n");
                exit(EXIT_FAILURE);
            }
        }
        // 4
        else if(type == END_SOURCE){
            region_num_list[(*num_source)-1]=num_region;
            num_region = 0;

        }
        else if(type == PORT){
          num = get_int(cfgLine,port);
          if (num != 1){
                printf("source region coord define error, check region_config file\n");
                exit(EXIT_FAILURE);
            }
        }
        // 5
        else if(type == END_FILE){
            // printf("==>end of file\n");
            return ;
        }
    }
}

void fitRegion(int* rect, int* whs, int *region_num_list, 
int* num_source){
    int tot_region = 0;
    // int n_region = 0;
    for(int i=0;i<(*num_source);i++){
        int n_region = region_num_list[i];
        int w = whs[i*2];
        int h = whs[i*2+1];
        // fit region size
        double r_w = TILED_OUTPUT_WIDTH / (double)w;
        double r_h = TILED_OUTPUT_HEIGHT / (double)h;
        // printf("--r_w: %f\n",r_w);
        // printf("--r_h: %f\n",r_h);
        if((r_w-1)==0 && (r_h - 1)==0) continue;
        else{
            for(int j=0;j<n_region;j++){
                // printf("--%d\n",rect[(tot_region+j)*4]);
                rect[(tot_region+j)*4] *= r_w;
                rect[(tot_region+j)*4+1] *= r_h;
                rect[(tot_region+j)*4+2] *= r_w;
                rect[(tot_region+j)*4+3] *= r_h;
            }
        }
        tot_region += n_region;
        n_region = 0;
    }
    return;
};



int
main (int argc, char *argv[])
{
  GMainLoop *loop = NULL;
  GstElement *pipeline = NULL, *streammux = NULL, *sink = NULL, *pgie = NULL,
      *queue1, *queue2, *queue3, *queue4, *queue5, *nvvidconv = NULL,
      *nvosd = NULL, *tiler = NULL;
#ifdef PLATFORM_TEGRA
  GstElement *transform = NULL;
#endif
  GstBus *bus = NULL;
  guint bus_watch_id;
  GstPad *tiler_src_pad = NULL;
  GstPad *osd_sink_pad = NULL;
  guint i, num_sources;
  guint tiler_rows, tiler_columns;
  guint pgie_batch_size;
  int num_sours = 0;
  int num_regions = 0;
  int Rects[12] = {0};
  int WHs[2] = {0};
  int regions_num_list[2]={0};
  int total_regions = 0;
  int port = 0;
  // printf("port:%d\n",port);
  community = argv[2];
  cameraid = argv[3];

  /* Check input arguments */
  if (argc < 2) {
    g_printerr ("Usage: %s <uri1> [uri2] ... [uriN] \n", argv[0]);
    return -1;
      }
  num_sources = argc - 3;

  /* Standard GStreamer initialization */
  gst_init (&argc, &argv);
  loop = g_main_loop_new (NULL, FALSE);

  /*------------------add-------------------*/

  FILE *fp;

  fp = fopen("region_config.txt", "r");
  if (fp == NULL){
      printf("Faill to open region confiiig file\n");
      return 0;
  }
 
  get_region(fp, &num_sours, Rects, WHs, regions_num_list, &total_regions, &port);
  fclose(fp);
  // fit region
  fitRegion(Rects, WHs, regions_num_list, &(num_sours));

	/*------------------------*/
  char c_port[10];
  sprintf(c_port,"%d",port);
  // printf("c_port:%s\n",c_port);
  char tcp[100] = "tcp://*:";
  strcat(tcp,c_port);
  printf("result:%s\n",tcp);

  // context = zmq_ctx_new();

  // publisher = zmq_socket(context, ZMQ_PUB);
 
  // int ret = zmq_bind(publisher, tcp);
  // assert(ret == 0);
	printf("publisher created!\n");
 
  if (num_sours != (argc -3)){
    printf("parsing region config file error, input stream and source num is not accordant!\n");
    exit(EXIT_FAILURE);
  }
  // set forbiden area, need to change
  // REGIONS = (region*)malloc(sizeof(region)*num_sources*3);
  

  // for (i = 0; i < num_sources; i++) {      
  //     region_init((REGIONS+3*i+0),Rects[0],Rects[1],Rects[2],Rects[3],STAY_TIME_HTRESH,what_time_is_it_now());
  //     region_init((REGIONS+3*i+1),Rects[4],Rects[5],Rects[6],Rects[7],STAY_TIME_HTRESH,what_time_is_it_now());
  //     region_init((REGIONS+3*i+2),Rects[8],Rects[9],Rects[10],Rects[11],STAY_TIME_HTRESH,what_time_is_it_now());
  // }

  // for(i = 0; i < num_sources; i++) {
  //   g_print("[region top ] %d \n",REGIONS[i].top);
  //   g_print("[region top ] %d \n",REGIONS[i+1].top);
  //   g_print("[region top ] %d \n",REGIONS[i+2].top);
  // }
  //
 

  /* Create gstreamer elements */
  /* Create Pipeline element that will form a connection of other elements */
  pipeline = gst_pipeline_new ("veolia-pipeline");

  /* Create nvstreammux instance to form batches from one or more sources. */
  streammux = gst_element_factory_make ("nvstreammux", "stream-muxer");

  if (!pipeline || !streammux) {
    g_printerr ("One element could not be created. Exiting.\n");
    return -1;
  }
  gst_bin_add (GST_BIN (pipeline), streammux);

  for (i = 0; i < num_sources; i++) {
    GstPad *sinkpad, *srcpad;
    gchar pad_name[16] = { };
    GstElement *source_bin = create_source_bin (i, argv[i + 1]);

    if (!source_bin) {
      g_printerr ("Failed to create source bin. Exiting.\n");
      return -1;
    }

    gst_bin_add (GST_BIN (pipeline), source_bin);

    g_snprintf (pad_name, 15, "sink_%u", i);
    sinkpad = gst_element_get_request_pad (streammux, pad_name);
    if (!sinkpad) {
      g_printerr ("Streammux request sink pad failed. Exiting.\n");
      return -1;
    }

    srcpad = gst_element_get_static_pad (source_bin, "src");
    if (!srcpad) {
      g_printerr ("Failed to get src pad of source bin. Exiting.\n");
      return -1;
    }

    if (gst_pad_link (srcpad, sinkpad) != GST_PAD_LINK_OK) {
      g_printerr ("Failed to link source bin to stream muxer. Exiting.\n");
      return -1;
    }

    gst_object_unref (srcpad);
    gst_object_unref (sinkpad);
  }

  /* Use nvinfer to infer on batched frame. */
  pgie = gst_element_factory_make ("nvinfer", "primary-nvinference-engine");

  /* Add queue elements between every two elements */
  queue1 = gst_element_factory_make ("queue", "queue1");
  queue2 = gst_element_factory_make ("queue", "queue2");
  queue3 = gst_element_factory_make ("queue", "queue3");
  queue4 = gst_element_factory_make ("queue", "queue4");
  queue5 = gst_element_factory_make ("queue", "queue5");

  /* Use nvtiler to composite the batched frames into a 2D tiled array based
   * on the source of the frames. */
  tiler = gst_element_factory_make ("nvmultistreamtiler", "nvtiler");

  /* Use convertor to convert from NV12 to RGBA as required by nvosd */
  nvvidconv = gst_element_factory_make ("nvvideoconvert", "nvvideo-converter");

  /* Create OSD to draw on the converted RGBA buffer */
  nvosd = gst_element_factory_make ("nvdsosd", "nv-onscreendisplay");

  /* Finally render the osd output */
#ifdef PLATFORM_TEGRA
  transform = gst_element_factory_make ("nvegltransform", "nvegl-transform");
#endif
  int no_show = 0;
  if (no_show){
    sink = gst_element_factory_make ("fakesink", "nvvideo-renderer");
  }
  else{
    sink = gst_element_factory_make ("nveglglessink", "nvvideo-renderer");
  }
  if (!pgie || !tiler || !nvvidconv || !nvosd || !sink) {
    g_printerr ("One element could not be created. Exiting.\n");
    return -1;
  }

#ifdef PLATFORM_TEGRA
  if(!transform) {
    g_printerr ("One tegra element could not be created. Exiting.\n");
    return -1;
  }
#endif

  g_object_set (G_OBJECT (streammux), "batch-size", num_sources, NULL);

  g_object_set (G_OBJECT (streammux), "live-source",1,NULL);

  g_object_set (G_OBJECT (streammux), "width", MUXER_OUTPUT_WIDTH, "height",
      MUXER_OUTPUT_HEIGHT,
      "batched-push-timeout", MUXER_BATCH_TIMEOUT_USEC, NULL);

  /* Configure the nvinfer element using the nvinfer config file. */
  g_object_set (G_OBJECT (pgie),
      "config-file-path", "Veolia_ai_config.txt", NULL);

  /* Override the batch-size set in the config file with the number of sources. */
  g_object_get (G_OBJECT (pgie), "batch-size", &pgie_batch_size, NULL);
  if (pgie_batch_size != num_sources) {
    g_printerr
        ("WARNING: Overriding infer-config batch-size (%d) with number of sources (%d)\n",
        pgie_batch_size, num_sources);
    g_object_set (G_OBJECT (pgie), "batch-size", num_sources, NULL);
  }

  tiler_rows = (guint) sqrt (num_sources);
  tiler_columns = (guint) ceil (1.0 * num_sources / tiler_rows);
  /* we set the tiler properties here */
  g_object_set (G_OBJECT (tiler), "rows", tiler_rows, "columns", tiler_columns,
      "width", TILED_OUTPUT_WIDTH, "height", TILED_OUTPUT_HEIGHT, NULL);

  g_object_set (G_OBJECT (nvosd), "process-mode", OSD_PROCESS_MODE,
       NULL);//"display-text", OSD_DISPLAY_TEXT,

  g_object_set (G_OBJECT (sink), "qos", 0, NULL);
  g_object_set (G_OBJECT (sink), "sync",FALSE,NULL);

  /* we add a message handler */
  bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline));
  bus_watch_id = gst_bus_add_watch (bus, bus_call, loop);
  gst_object_unref (bus);

  /* Set up the pipeline */
  /* we add all elements into the pipeline */
#ifdef PLATFORM_TEGRA
  gst_bin_add_many (GST_BIN (pipeline), queue1, pgie, queue2, tiler, queue3,
      nvvidconv, queue4, nvosd, queue5, transform, sink, NULL);
  /* we link the elements together
   * nvstreammux -> nvinfer -> nvtiler -> nvvidconv -> nvosd -> video-renderer */
  if (!gst_element_link_many (streammux, queue1, pgie, queue2, tiler, queue3,
        nvvidconv, queue4, nvosd, queue5, transform, sink, NULL)) {
    g_printerr ("Elements could not be linked. Exiting.\n");
    return -1;
  }
#else
gst_bin_add_many (GST_BIN (pipeline), queue1, pgie, queue2, tiler, queue3,
    nvvidconv, queue4, nvosd, queue5, sink, NULL);
  /* we link the elements together
   * nvstreammux -> nvinfer -> nvtiler -> nvvidconv -> nvosd -> video-renderer */
  if (!gst_element_link_many (streammux, queue1, pgie, queue2, tiler, queue3,
        nvvidconv, queue4, nvosd, queue5, sink, NULL)) {
    g_printerr ("Elements could not be linked. Exiting.\n");
    return -1;
  }
#endif

  /* Lets add probe to get informed of the meta data generated, we add probe to
   * the sink pad of the osd element, since by that time, the buffer would have
   * had got all the metadata. */
  tiler_src_pad = gst_element_get_static_pad (pgie, "src");
  if (!tiler_src_pad)
    g_print ("Unable to get src pad\n");
  else
  {
    gst_pad_add_probe (tiler_src_pad, GST_PAD_PROBE_TYPE_BUFFER,
        tiler_src_pad_buffer_probe, NULL, NULL);
    //gst_pad_add_probe (tiler_src_pad, GST_PAD_PROBE_TYPE_BUFFER,
    //nvinfer_src_pad_buffer_probe, NULL, NULL);
  }
  gst_object_unref (tiler_src_pad);
  
  osd_sink_pad = gst_element_get_static_pad (nvosd, "sink");
  if (!osd_sink_pad)
    g_print ("Unable to get sink pad\n");
  else
    gst_pad_add_probe (osd_sink_pad, GST_PAD_PROBE_TYPE_BUFFER,
        osd_sink_pad_buffer_res_probe, NULL, NULL);
  gst_object_unref (osd_sink_pad);


  /* Set the pipeline to "playing" state */
  g_print ("Now playing:");
  for (i = 0; i < num_sources; i++) {
    g_print (" %s,", argv[i + 1]);
  }
  g_print ("\n");
  gst_element_set_state (pipeline, GST_STATE_PLAYING);

  /* Wait till pipeline encounters an error or EOS */
  g_print ("Running...\n");
  g_main_loop_run (loop);

  /* Out of the main loop, clean up nicely */
  g_print ("Returned, stopping playback\n");
  gst_element_set_state (pipeline, GST_STATE_NULL);
  g_print ("Deleting pipeline\n");
  gst_object_unref (GST_OBJECT (pipeline));
  g_source_remove (bus_watch_id);
  g_main_loop_unref (loop);
  free(REGIONS);
  return 0;
}
